import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface User {
  id: number;
  username: string;
  email: string;
  is_superuser: boolean;
  is_active: boolean;
  roles?: string[];
  permissions?: string[];
  last_login_at?: string;
}

interface AuthState {
  user: User | null;
  token: string | null;
  refreshToken: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
  
  // Actions
  login: (email: string, password: string) => Promise<boolean>;
  register: (email: string, password: string, username?: string) => Promise<boolean>;
  logout: () => void;
  refreshAccessToken: () => Promise<boolean>;
  getCurrentUser: () => Promise<boolean>;
  updateUser: (updatedUser: Partial<User>) => void;
  clearError: () => void;
  setLoading: (loading: boolean) => void;
  initializeAuth: () => Promise<void>;
  clearAuthState: () => void; // 添加清除认证状态的方法
}

// 防止并发初始化的标志
let isInitializing = false;
let initPromise: Promise<void> | null = null;

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      refreshToken: null,
      isAuthenticated: false,
      isLoading: true, // 初始为 true，等待验证完成
      error: null,

      login: async (email: string, password: string) => {
        set({ isLoading: true, error: null });
        
        try {
          const response = await fetch('/api/v1/auth/login', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email, password }),
          });

          if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.detail || '登录失败');
          }

          const data = await response.json();
          
          set({
            token: data.access_token,
            refreshToken: data.refresh_token,
            isAuthenticated: true,
            isLoading: false,
            error: null,
          });

          // 获取用户信息
          await get().getCurrentUser();
          return true;
        } catch (error) {
          set({
            isLoading: false,
            error: error instanceof Error ? error.message : '登录失败',
            isAuthenticated: false,
            token: null,
            refreshToken: null,
            user: null,
          });
          return false;
        }
      },

      register: async (email: string, password: string, username?: string) => {
        set({ isLoading: true, error: null });
        
        try {
          const response = await fetch('/api/v1/auth/register', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
              email, 
              password, 
              username: username || email.split('@')[0] 
            }),
          });

          if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.detail || '注册失败');
          }

          set({ isLoading: false, error: null });
          return true;
        } catch (error) {
          set({
            isLoading: false,
            error: error instanceof Error ? error.message : '注册失败',
          });
          return false;
        }
      },

      logout: () => {
        set({
          user: null,
          token: null,
          refreshToken: null,
          isAuthenticated: false,
          error: null,
        });
      },

      refreshAccessToken: async () => {
        const { refreshToken } = get();
        if (!refreshToken) {
          console.log('没有refresh token，无法刷新');
          return false;
        }

        try {
          // 将refresh_token作为查询参数发送
          const response = await fetch(`/api/v1/auth/refresh?refresh_token=${encodeURIComponent(refreshToken)}`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
          });

          if (!response.ok) {
            console.log('刷新token失败，状态码:', response.status);
            const errorData = await response.json().catch(() => ({}));
            console.log('刷新token错误信息:', errorData);
            throw new Error('刷新令牌失败');
          }

          const data = await response.json();
          console.log('token刷新成功');
          set({
            token: data.access_token,
            isAuthenticated: true,
          });

          return true;
        } catch (error) {
          console.error('刷新token异常:', error);
          // 刷新失败，清空所有认证信息
          set({
            token: null,
            refreshToken: null,
            isAuthenticated: false,
            user: null,
          });
          return false;
        }
      },

      getCurrentUser: async () => {
        const { token } = get();
        if (!token) {
          console.log('没有token，无法获取用户信息');
          return false;
        }

        try {
          const response = await fetch('/api/v1/auth/me', {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json',
            },
          });

          if (!response.ok) {
            console.log('获取用户信息失败，状态码:', response.status);
            if (response.status === 401) {
              console.log('Token已过期，需要重新登录');
              // Token过期，但不在这里清空状态，由调用方处理
            }
            const errorData = await response.json().catch(() => ({}));
            console.log('获取用户信息错误信息:', errorData);
            throw new Error('获取用户信息失败');
          }

          const userData = await response.json();
          console.log('获取到的用户数据:', userData);
          
          // 根据项目规范：成功获取用户信息后必须设置isAuthenticated为true
          set({
            user: {
              id: userData.user_id || userData.id,
              username: userData.username,
              email: userData.email,
              is_superuser: userData.is_superuser || false,
              is_active: userData.is_active !== false,
              roles: userData.roles || [],
              permissions: userData.permissions || [],
              last_login_at: userData.last_login_at,
            },
            isAuthenticated: true, // 重要：确保认证状态与用户数据同步更新
          });

          return true;
        } catch (error) {
          console.error('获取用户信息失败:', error);
          return false;
        }
      },

      clearError: () => set({ error: null }),
      setLoading: (loading: boolean) => set({ isLoading: loading }),
      
      updateUser: (updatedUser: Partial<User>) => {
        const currentUser = get().user;
        if (currentUser) {
          set({ 
            user: { ...currentUser, ...updatedUser } 
          });
        }
      },
      
      initializeAuth: async () => {
        // 防止并发初始化
        if (isInitializing && initPromise) {
          console.log('认证初始化正在进行中，等待完成');
          return initPromise;
        }
        
        isInitializing = true;
        
        const { token, refreshToken, isAuthenticated } = get();
        
        console.log('正在初始化认证状态...', { 
          hasToken: !!token, 
          hasRefreshToken: !!refreshToken,
          isAuthenticated: isAuthenticated
        });
        
        // 如果没有token，直接设置为未认证状态
        if (!token) {
          console.log('没有token，设置为未认证状态');
          set({ 
            isLoading: false, 
            isAuthenticated: false,
            user: null,
            token: null,
            refreshToken: null
          });
          isInitializing = false;
          return;
        }
        
        // 如果已经有认证状态且用户信息完整，直接完成初始化
        if (isAuthenticated && get().user) {
          console.log('已有认证状态和用户信息，直接完成初始化');
          set({ isLoading: false });
          isInitializing = false;
          return;
        }
        
        // 创建初始化Promise
        initPromise = (async () => {
          try {
            // 尝试获取用户信息
            console.log('尝试获取用户信息...');
            const success = await get().getCurrentUser();
            
            if (success) {
              console.log('用户信息获取成功，已设置为已认证状态');
              // getCurrentUser 已经设置了 isAuthenticated = true
            } else if (refreshToken) {
              console.log('获取用户信息失败，尝试刷新token...');
              // 尝试刷新token
              const refreshSuccess = await get().refreshAccessToken();
              if (refreshSuccess) {
                console.log('token刷新成功，重新获取用户信息...');
                const retrySuccess = await get().getCurrentUser();
                if (retrySuccess) {
                  console.log('token刷新成功，用户信息获取成功');
                  // getCurrentUser 已经设置了 isAuthenticated = true
                } else {
                  console.log('token刷新成功但用户信息获取失败，清空状态');
                  set({
                    user: null,
                    token: null,
                    refreshToken: null,
                    isAuthenticated: false,
                  });
                }
              } else {
                console.log('token刷新失败，清空状态');
                // refreshAccessToken 已经清空了状态
              }
            } else {
              console.log('没有refresh token，清空状态');
              set({
                user: null,
                token: null,
                refreshToken: null,
                isAuthenticated: false,
              });
            }
          } catch (error) {
            console.error('认证初始化失败:', error);
            set({
              user: null,
              token: null,
              refreshToken: null,
              isAuthenticated: false,
            });
          } finally {
            console.log('认证初始化完成，当前状态:', {
              isAuthenticated: get().isAuthenticated,
              hasUser: !!get().user,
              hasToken: !!get().token
            });
            // 确保isLoading被设置为false
            set({ isLoading: false });
            isInitializing = false;
            initPromise = null;
          }
        })();
        
        return initPromise;
      },
      
      clearAuthState: () => {
        set({
          user: null,
          token: null,
          refreshToken: null,
          isAuthenticated: false,
          error: null,
        });
      },
    }),
    {
      name: 'auth-store',
      partialize: (state: AuthState) => ({
        token: state.token,
        refreshToken: state.refreshToken,
        // 只有动态认证成功时才持久化isAuthenticated
        isAuthenticated: state.isAuthenticated && !!state.user && !!state.token,
        user: state.user,
      } as Partial<AuthState>),
      // 改善持久化的重水化逻辑
      onRehydrateStorage: () => (state) => {
        console.log('正在重水化认证状态:', state);
        if (state) {
          // 重水化后初始设置为加载状态，等待初始化完成
          state.isLoading = true;
          // 如果没有token或用户信息，直接设置为未认证
          if (!state.token || !state.user) {
            state.isAuthenticated = false;
          }
        }
      },
      // 添加版本控制和迁移函数来解决警告
      version: 1,
      migrate: (persistedState: any, version: number) => {
        // 如果版本是0或者没有版本，则执行迁移
        if (version === 0 || version === undefined) {
          // 返回默认状态，或者根据需要迁移旧状态
          return {
            user: null,
            token: null,
            refreshToken: null,
            isAuthenticated: false,
            isLoading: true,
            error: null,
            ...persistedState,
          };
        }
        return persistedState;
      },
    }
  )
);